import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter/gestures.dart';
import 'package:get/get.dart';
import '../../modules/login/request/user_request.dart';
import 'app_manager.dart';
import 'const.dart';
import '../networking/http_manager.dart';
import '../pay_manager/wechat_pay/wechat_manager.dart';
import '../umemg_manager/umeng_manager.dart';
import '../widget/common.dart';
import '../widget/my_dialog.dart';
import 'dart:io';

class AppLaunching {

  static Future launching() async {
    await AppManager.getDeviceInfo();
    await AppManager.getUserData();
    await AppManager.getAuthState();
    await AppLaunching.setupNetwork();
    await AppLaunching.isFirstInstall();
    // await AppLaunching.requestPopAdvert();
    // await AppLaunching.requestActiveAdvert();
    await AppLaunching.requestUserToken();
    WechatManager.instance.register();
    debugPrint("appLaunching()执行完毕");
  }

  static isFirstInstall() async {
    final value = localStorageRead("isFirstInstall") ?? true;
    AppManager.isFirstInstall = value;
    if (!value) {
      registerUmengPush();
    }
  }

  static showProtocol() {
    if (AppManager.isFirstInstall == true) {
      // value 没有值为首次安装，或未同意隐私服务协议。1
      debugPrint("isFirstInstall() 执行完毕！App安装成功，第一次安装");
      // 延迟到用户同意隐私服务协议后保寸安装状态
      // await localStorageWrite("isFirstInstall", fase);
      debugPrint("开始展示隐私协议");
      AppLaunching.readUserInfoTap();
    }else {
      // debugPrint("_isFirstInstall() 执行完毕！App安装成功，非首次安装");
      // AppLaunching._getSignStateHttp();
      registerUmengPush();
    }
  }

  // 配置网络
  static setupNetwork() async {
    HttpManager.setEnableLog(true);
    final debug = localStorageRead("isDebugBaseUrl");
    HttpManager.baseUrl(debug == true ? baseURLTest : baseURL);
    HttpManager.setHeaders({"DeviceCode": AppManager.uuid});
    HttpManager.setHeaders({"User-Agent": "AutoSteward/${AppManager.version}(iOS)"});
    HttpManager.setHeaders({"DeviceModel": AppManager.deviceModel});
    var token = AppManager.user == null ? "" : AppManager.user!.userToken!;
    HttpManager.setHeaders({"UserToken": token});
    final sid = AppManager.currentShop?.shopId;
    Map<String, dynamic> baseParam = {"shopInfoId": sid, "shopId": sid};
    HttpManager.setBaseParam(baseParam);
    debugPrint("HttpManager.baseParam = $baseParam");
    debugPrint("setupNetwork() 执行完毕！HttpManager.baseUrl = ${HttpManager.instance.dio.options.baseUrl}");

    if (localStorageRead("isDebugBaseUrl") == true) {
      AfterDelay.milliseconds(3000, callBack: (){
        showMessage("请注意！当前为测试环境！");
      });
    }
  }

  static changeNetworkBaseURL({String? host}) {
    if (host != null) {
      localStorageWrite("isDebugBaseUrl", true);
      if (host.startsWith("http") != true) host = "http://$host";
      HttpManager.baseUrl(host);
      showMessage("已连接 ${local_hosts[host]} 的主机");
      debugPrint('=====已连接${local_hosts[host]}的主机=====');
    }else {
      if (localStorageRead("isDebugBaseUrl") == true) {
        HttpManager.baseUrl(baseURL);
        localStorageWrite("isDebugBaseUrl", false);
        showMessage("已切换正式环境");
        debugPrint('=====已切换正式环境=====');
      }else {
        HttpManager.baseUrl(baseURLTest);
        localStorageWrite("isDebugBaseUrl", true);
        showMessage("已切换测试环境");
        debugPrint('=====已切换测试环境=====');
      }
    }
    AppLaunching.requestUserToken();
  }

  // 根据设备 uuid 获取 userToken
  static Future requestUserToken() async {
    await UserRequest.getUserToken(AppManager.uuid);
  }

  // 展示用户协议
  static void readUserInfoTap() async {
    showAlertDialog(
        title: "隐私政策",
        margin: const EdgeInsets.only(left: 30, right: 30),
        messageTextSpan: TextSpan(children: [
          const TextSpan(
            text: '依据最新的监管要求更新了用户隐私保护协议，并且禁止软件获取不相关的权限和数据，以此来最大限度的保护用户的利益。为此我们明确了用户的查询、更正和删除其个人信息的方式。\n请仔细阅读', style: TextStyle(fontSize: 16, color: Colors.black, height: 1.5),
          ),
          TextSpan(
              text: '《服务协议》',style: const TextStyle(fontSize: 16, color: Colors.blue, decorationColor: Colors.blue,height: 1.5),
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  Get.toNamed("/WebViewPage", arguments: {
                    "url" : "https://echelianhtml.ygxpt.com/agreement/index.html",
                    "title" : "服务协议",
                  });
                }),
          const TextSpan(
            text: '和',style: TextStyle(fontSize: 16, color: Colors.black,height: 1.5),
          ),
          TextSpan(
              text: '《隐私政策》',style: const TextStyle(fontSize: 16, color: Colors.blue, decorationColor: Colors.blue,height: 1.5),
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  Get.toNamed("/WebViewPage", arguments: {
                    "url" : "https://echelianhtml.ygxpt.com/privacy/index.html",
                    "title" : "用户隐私政策",
                  });
                }
          ),
          const TextSpan(
            text: '尤其是加粗和划横线的内容，并了解我们对您个人信息的处理规则。',style: TextStyle(fontSize: 16, color: Colors.black,height: 1.5),
          ),

        ]),
        confirmText: "同意",
        confirm: () async {
          dismissAlertDialog();
          AppManager.isFirstInstall = false;
          await localStorageWrite("isFirstInstall", false);
          debugPrint("用户同意个人隐私协议");
          registerUmengPush();
          await AppLaunching._setSignStateHttp();
        },
        cancel: () {
          dismissAlertDialog();
          showAlertDialog(
              title: "温馨提示",
              messageTextSpan: TextSpan(children: [
                const TextSpan(
                  text: '为了在提供服务的同时，更好的保障您的合法权益，请仔细阅读我们的', style: TextStyle(fontSize: 16, color: Colors.black, height: 1.5),
                ),
                TextSpan(
                    text: '《服务协议》',style: const TextStyle(fontSize: 16, color: Colors.blue, decorationColor: Colors.blue,height: 1.5),
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        Get.toNamed("/WebViewPage", arguments: {
                          "url" : "https://echelianhtml.ygxpt.com/agreement/index.html",
                          "title" : "服务协议",
                        });
                      }),
                const TextSpan(
                  text: '和',style: TextStyle(fontSize: 16, color: Colors.black,height: 1.5),
                ),
                TextSpan(
                    text: '《隐私政策》',style: const TextStyle(fontSize: 16, color: Colors.blue, decorationColor: Colors.blue,height: 1.5),
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        Get.toNamed("/WebViewPage", arguments: {
                          "url" : "https://echelianhtml.ygxpt.com/privacy/index.html",
                          "title" : "用户隐私政策",
                        });
                      }
                ),
                const TextSpan(
                  text: '我们尊重您的选择，如果您不同意，我们无法为您提供相应的服务，App也将会退出。',style: TextStyle(fontSize: 16, color: Colors.black,height: 1.5),
                ),

              ]),
              confirmText: "同意",
              confirm: () async {
                dismissAlertDialog();
                AppManager.isFirstInstall = false;
                await localStorageWrite("isFirstInstall", false);
                debugPrint("用户同意个人隐私协议");
                registerUmengPush();
                await AppLaunching._setSignStateHttp();
              },
              cancelText: "不同意",
              cancel: () {
                debugPrint("用户不同意协议，App已退出");
                exit(0);
              }
          );
        }
    );
  }

  static registerUmengPush() {
    AfterDelay.milliseconds(500, callBack: () async {
      // 为了优化界面效果，需要等待隐私协议框的动画消失后，再弹出提示授权通知框。
      // UmengPushManager.enableLog(true);
      // UmengPushManager.instance.init();
      // UmengPushManager.instance.register();
      // debugPrint("deviceToken:${await UmengPushManager.getDeviceToken()}");
    });
  }

  // 设置用户隐私协议的签名状态
  static Future _setSignStateHttp() async {
    if (AppManager.uuid.isNotEmpty) {
      var result = await UserRequest.uploadingSigned(AppManager.uuid);
      if (result.success) {
        debugPrint("用户同意个人隐私协议，已上传服务器！");
      }
    }else {
      debugPrint("上报用户隐私以阅读的签名名状态：uuid为空!");
    }
  }

  // 从 App Store 检测新版本
  static Future checkAppVersionUpdate() async {
    final info = await getAppStoreInfo();
    int state = info!.results!.first.version!.compareTo(AppManager.version);
    if (state > 0 && AppManager.isShowUpload == false) {
      // App Store版本高于本地版本
      AppManager.isShowUpload = true;
      showAlertDialog(
        title: "检测到新版本",
        message: "是否升级到${info.results!.first.version}版本？",
        margin: const EdgeInsets.only(left: 20, right: 20),
        content: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SingleChildScrollView(
              child: RichText(
                text: TextSpan(children: [
                  TextSpan(
                    text: info.results!.first.releaseNotes!,
                    // text: "1. 新增了优惠券批量审核的功能\n2. 重构了客户关怀界面逻辑与操作流程\n3. 优化了登录速度并且取消了生物认证\n4. 优化了物业服务租赁物业水电表问题\n5. 优化了添加潜客不展示品牌 Logo 问题\n6. 修改了潜客状态时间轴数据错乱的问题\n7. 修改了潜客跟进备注框被键盘遮挡的问题\n8. 修改了切换账号首页店铺名称未更改的问题\n9. 修改了潜客了列表点击手机号无法呼叫的问题\n",
                    style: const TextStyle(fontSize: 16, color: Colors.black, height: 1.5),
                  ),
                ]),
              ),
            ),
          ],
        ),
        confirmText: "立即更新",
        cancelText: "以后再说",
        buttonVertical: true,
        confirm: () async {
          dismissAlertDialog();
          AppManager.isShowUpload = false;
          launchUrl(Uri(scheme: 'https', host: 'itunes.apple.com', path: '/cn/app/$AppStoreID'));
        },
        cancel: () {
          dismissAlertDialog();
          AppManager.isShowUpload = false;
        },
      );
    }
  }




  // 查看 App Store 是否有新版本
  static Future<AppStoreInfoModel?> getAppStoreInfo() async {
    if (Platform.isIOS) {
      return await _iOSAppStoreInfo();
    } else if (Platform.isAndroid) {

    } else {

    }
    return null;
  }

  static Future<AppStoreInfoModel?> _iOSAppStoreInfo() async {
    DateTime now = DateTime.now();
    final timestamp = now.millisecondsSinceEpoch.toString();
    // 用GET方法请求，GET请求会有缓存，导致获取版本不及时，换为POST
    // 拼接时间戳，防止服务器对请求进行对 get 请求做缓存处理，或者使用 post 请求。
    final url = 'https://itunes.apple.com/cn/lookup?id=$AppStoreID&timestamp=$timestamp';
    final resObject = await Dio().post(url);
    if (resObject.data is String) {
      final jsonResponse = json.decode(resObject.data);
      if (jsonResponse is Map<String, dynamic>) {
        return AppStoreInfoModel.fromJson(jsonResponse);
      }
    } else if (resObject.data is Map<String, dynamic>) {
      return AppStoreInfoModel.fromJson(resObject.data);
    }
    return null;
  }
}


// =============================================================================
//                                AppStoreInfoModel
// =============================================================================
class AppStoreInfoModel {
  num? resultCount;
  List<AppStoreInfoModelResults>? results;
  AppStoreInfoModel(this.resultCount,this.results);
  factory AppStoreInfoModel.fromJson(Map<String, dynamic> json) {
    return AppStoreInfoModel(
        json['resultCount'] as num,
        (json['results'] as List).map((i) => AppStoreInfoModelResults.fromJson(i)).toList()
    );
  }
}

class AppStoreInfoModelResults {
  String? version;
  String? releaseNotes;
  AppStoreInfoModelResults(this.version,this.releaseNotes);
  factory AppStoreInfoModelResults.fromJson(Map<String, dynamic> json) {
    return AppStoreInfoModelResults(
        json['version'] as String,
        json['releaseNotes'] as String
    );
  }
}